package ustc.xiaoyang.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ustc.xiaoyang.mapper.StudentMapper;
import ustc.xiaoyang.pojo.PageResult;
import ustc.xiaoyang.pojo.Student;
import ustc.xiaoyang.pojo.dto.StudentPageQueryDTO;
import ustc.xiaoyang.service.StudentService;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    private final StudentMapper studentMapper;
    public StudentServiceImpl(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }

    @Override
    public PageResult<Student> pageList(StudentPageQueryDTO studentPageQueryDTO) {
        PageHelper.startPage(studentPageQueryDTO.getPage(), studentPageQueryDTO.getPageSize());
        List<Student> studentList = studentMapper.pageList(studentPageQueryDTO);
        Page<Student> p = (Page<Student>) studentList;
        return new PageResult<>(p.getTotal(), p.getResult());

    }

    @Override
    public void add(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        student.setCreateTime(LocalDateTime.now());
        studentMapper.add(student);
    }

    @Override
    public Student getById(Integer id) {
        return studentMapper.getById(id);
    }

    @Override
    public void update(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        studentMapper.deleteByIds(ids);
    }

    @Transactional
    @Override
    public void updateViolation(Integer id, Integer score) {
        LocalDateTime updateTime = LocalDateTime.now();
        studentMapper.updateViolation(id, score, updateTime);
    }
}
